package com.company.cyxmall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.company.common.constant.WareConstant;
import com.company.cyxmall.ware.entity.PurchaseDetailEntity;
import com.company.cyxmall.ware.service.PurchaseDetailService;
import com.company.cyxmall.ware.service.WareSkuService;
import com.company.cyxmall.ware.vo.MergeVo;
import com.company.cyxmall.ware.vo.PurchaseDoneVo;
import com.company.cyxmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.common.utils.PageUtils;
import com.company.common.utils.Query;

import com.company.cyxmall.ware.dao.PurchaseDao;
import com.company.cyxmall.ware.entity.PurchaseEntity;
import com.company.cyxmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }


    @Override
    @Transactional
    public void saveMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();

        List<PurchaseDetailEntity> collect = items.stream().map((item) -> {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item);

            if (detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
                    detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()) {

                if (purchaseId == null) {
                    PurchaseEntity entity = new PurchaseEntity();
                    entity.setCreateTime(new Date());
                    entity.setUpdateTime(new Date());
                    entity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
                    this.save(entity);

                    detailEntity.setId(item);
                    detailEntity.setPurchaseId(entity.getId());
                    detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return detailEntity;
                } else {
                    PurchaseEntity purchaseEntity = new PurchaseEntity();
                    purchaseEntity.setId(purchaseId);
                    purchaseEntity.setUpdateTime(new Date());
                    this.updateById(purchaseEntity);

                    detailEntity.setId(item);
                    detailEntity.setPurchaseId(purchaseId);
                    detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                    return detailEntity;
                }
            } else {
                return null;
            }
        }).collect(Collectors.toList());

        if (collect == null || collect.size() == 0) {
            return;
        } else {
            purchaseDetailService.updateBatchById(collect);
        }
    }


    @Override
    @Transactional
    public void received(List<Long> ids) {
        // 1.确认要领取的采购单为新建或已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map((id) -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter((entity) -> {
            Integer status = entity.getStatus();
            if (status == WareConstant.PurchaseStatusEnum.CREATED.getCode() || status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map((entity) -> {
            entity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            entity.setUpdateTime(new Date());
            return entity;
        }).collect(Collectors.toList());
        // 2.改变采购单的状态
        this.updateBatchById(purchaseEntities);

        // 3.改变采购需求的状态
        purchaseEntities.forEach((entity) -> {
            Long id = entity.getId();
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.getPurchaseDetailsByAssigneeId(id);

            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map((item) -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
//                item.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        });

    }


    @Override
    @Transactional
    public void finish(PurchaseDoneVo vo) {
        // 1.改变采购需求项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = vo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>(10);
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3.将成功采购的进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        // 2.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(vo.getId());
        purchaseEntity.setStatus(flag == true? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}